<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="4" :xs="24">
                <div class="head-container">
                    <el-input v-model="placePointName" @keyup.enter.native="getAllShop" @blur="getAllShop"
                        placeholder="请输入门店名称" clearable size="small" prefix-icon="el-icon-search"
                        style="margin-bottom: 20px" />
                </div>
                <div class="head-container list-all">
                    <div :class="[placePointNameIndex == index ? 'active' : '']" @click="handleShop(item, index)"
                        v-for="(item, index) in shopList" :key="index">{{ item.placePointName }}</div>
                </div>
            </el-col>
            <el-col :span="20" :xs="24">
                <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
                    <el-form-item label="门店名称" prop="placePointName">
                        <el-input v-model="queryParams.placePointName" placeholder="请输入内容" clearable
                            style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="店员名称" prop="nickName">
                        <el-input v-model="queryParams.nickName" placeholder="请输入内容" clearable style="width: 240px"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-select v-model="queryParams.status" placeholder="请选择状态">
                            <el-option v-for="dict in dict.type.sys_clerk_state" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search"  class="add"
                            @click="handleQuery">查询</el-button>
                        <el-button icon="el-icon-refresh"  class="delBtn" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:user:add']" type="primary" plain icon="el-icon-plus" class="add"
                            @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:user:remove']" type="danger" plain icon="el-icon-delete" :disabled="multiple"
                            @click="handleDelete">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">

                        <el-upload v-hasPermi="['system:user:import']" class="upload-demo" :action="uploadUrl" :before-upload="handleBeforeUpload"
                            :on-success="handleUploadSuccess" :headers="headers" :limit="1" :show-file-list="false">
                            <el-button type="primary" plain icon="el-icon-upload2" class="add">导入</el-button>
                        </el-upload>
                    </el-col>

                    <el-col :span="1.5">
                        <el-button v-hasPermi="['system:user:importTemplate']" type="primary" plain icon="el-icon-download" class="delBtn"
                            @click="importTemplate">导入模板下载</el-button>
                    </el-col>


                    <right-toolbar :show-search.sync="showSearch" @queryTable="getListData" />
                </el-row>
                <el-table ref="table" :key="tableKey" v-loading="loading" :data="roleList" style="margin-top: 20px"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="名称" prop="nickName" />
                    <el-table-column label="门店" prop="placePointName" />
                    <el-table-column label="工号" prop="userName" />
                    <el-table-column label="角色" prop="roleName" />
                    <el-table-column label="状态" align="center">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.sys_clerk_state" :value="scope.row.status" />
                        </template>
                    </el-table-column>


                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button  v-hasPermi="['system:user:edit']" size="mini" type="text" icon="el-icon-edit"
                                @click="handleUpdate(scope.row)">编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getListData" />
            </el-col>
        </el-row>

        <el-dialog :title="title" :visible.sync="open" width="786px" append-to-body>
            <el-form ref="addForm" :model="addForm" :rules="addRules" label-position="top">
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="店员名称" prop="nickName">
                            <el-input v-model="addForm.nickName" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="工号" prop="userName">
                            <el-input v-model="addForm.userName" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="角色" prop="roleId">
                            <el-select v-model="addForm.roleId" placeholder="请选择内容">
                                <el-option v-for="(item, index) in roleSelAll" :key="index" :label="item.roleName"
                                    :value="item.roleId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="门店" prop="placePointId">
                            <el-select v-model="addForm.placePointId" placeholder="请选择内容">
                                <el-option v-for="(item, index) in placePointAll" :key="index"
                                    :label="item.placePointName" :value="item.placePointId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="修改密码" :prop="addForm.userId?'aaa':'password'">
                            <el-input type="password" show-password v-model="addForm.password" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否开启" prop="status">
                            <el-switch v-model="addForm.status" active-value="0" inactive-value="1"
                                active-color="#0052d9" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" class="add" @click="submitForm">{{
            addForm.userId ? "确认编辑" : "确认添加"
        }}</el-button>
            </div>
            <el-dialog :visible.sync="dialogVisible" :modal="false">
                <el-image :src="dialogImageUrl" :fit="fit"></el-image>
            </el-dialog>
        </el-dialog>
    </div>
</template>

<script>
import {
    getList,
    addData,
    editData,
    delData,
} from "@/api/medicalShopManage/index";
import { listPoint } from "@/api/bus/point";
import { getToken } from "@/utils/auth";
import { getUserProfile } from "@/api/system/user";
import { listRole } from "@/api/system/role";
export default {
    name: "Role",
    dicts: ["sys_clerk_state"],
    data() {
        return {
            fit:'none',
            placePointAll: [],
            roleSelAll: [],
            shopList: [],
            placePointName: '',
            placePointNameIndex: 0,
            dialogVisible: false,
            dialogImageUrl: "",
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            uploadUrl:
                process.env.VUE_APP_BASE_API + "/system/user/importData", // 上传的图片服务器地址
            headers: {
                Authorization: "Bearer " + getToken(),
            },

            user: {},
            fileList: [],
            title: "添加",
            open: false,
            tableKey: 0,
            // 遮罩层
            loading: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 10,
            // 角色表格数据
            roleList: [],
            // 查询参数
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                placePointName: "",
                nickName: "",
                placePointId: ""
            },
            addForm: {
                nickName: "",
                password: "",
                placePointId: "",
                roleId: "",
                status: "0",
                userName: ""
            },
            addRules: {
                nickName: [
                    { required: true, message: "内容不能为空", trigger: "blur" },
                ],
                password: [
                    { required: true, message: "内容不能为空", trigger: "blur" },
                ],
                placePointId: [
                    { required: true, message: "请选择内容", trigger: "blur" },
                ],
                roleId: [
                    { required: true, message: "请选择内容", trigger: "blur" },
                ],
                status: [
                    { required: true, message: "内容不能为空", trigger: "blur" },
                ],
                userName: [
                    { required: true, message: "内容不能为空", trigger: "blur" },
                ],
            },
            systemList: [],
        };
    },
    created() {
        this.getListData();
        this.getAllShop()
        getUserProfile().then((res) => {
            this.user = res.data;
        });
        listRole({}).then(response => {
            this.roleSelAll = response.rows;
        }
        );
    },
    methods: {
        //获取门店
        getAllShop() {
            listPoint({ placePointName: this.placePointName }).then(res => {
                if (res.data && res.data.records) {
                    this.placePointAll = JSON.parse(JSON.stringify(res.data.records))
                    this.shopList = res.data.records
                    this.shopList.splice(0, 0, { placePointId: '', placePointName: '全部' })
                }

            })
        },
        //点击门店
        handleShop(row,index) {
            this.placePointNameIndex =index
                this.queryParams.placePointId = row.placePointId
            this.getListData();
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
            console.log(file.url);
        },
        // 上传前校检格式和大小
    handleBeforeUpload(file) {
      console.log(file);
      const type = [
        ".xlsx",
        ".xls",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      ];
      const isJPG = type.includes(file.type);
      // 检验文件格式
      if (!isJPG) {
        this.$message.error(`文件格式错误!`);
        return false;
      }
      return true;
    },
    handleUploadSuccess(res, file) {
      // 如果上传成功
      if (res.code == 200) {
        this.getListData();
      } else {
        this.$message.error("文件上传失败");
      }
    },
       
        // 多选框选中数据
        handleSelectionChange(selection) {

            this.ids = selection.map((item) => item.userId);
            console.log(this.ids)
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 查询列表 */
        getListData() {
            this.loading = true;
            getList({
                ...this.queryParams
            }).then((response) => {
                this.roleList = response.data.records;
                this.total = response.data.total || 0;
                this.loading = false;
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.$nextTick(() => {
                this.getListData();
            });
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams.pageNum = 1;
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 添加按钮操作 */
        handleAdd() {
            this.title = "添加";
            this.open = true;
            this.reset();
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.title = "编辑";
            console.log(row);
            this.addForm = JSON.parse(JSON.stringify(row))
            this.open = true;
        },
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.addForm = {
                phone: "",
                signTime: "",
                description: "",
                imageUrls: [],
                remark: "",
                status:'0'
            };
            this.fileList = [];
            this.resetForm("addForm");
        },
        /** 按钮操作 */
        handleDelete(row) {
            const roleIds = row.userId || this.ids;
            this.$modal.confirm('是否确认删除店员编号为"' + roleIds + '"的数据项？').then(function () {
                return delData(roleIds);
            }).then(() => {
                this.getListData();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download('system/user/importTemplate', {
            }, `店员导入模板_${new Date().getTime()}.xlsx`)
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["addForm"].validate((valid) => {
                if (valid) {

                    if (this.addForm.userId) {
                        editData({
                            ...this.addForm,
                            contactByName: this.user.nickName,
                        }).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getListData();
                        });
                    } else {
                        addData({
                            ...this.addForm,
                            contactByName: this.user.nickName,
                        }).then((response) => {
                            this.$modal.msgSuccess("添加成功");
                            this.open = false;
                            this.getListData();
                        });
                    }
                }
            });
        },
    },
};
</script>
<style lang="scss" scoped>
.list-all {
    margin: 0 32px;

    div {
        font-size: 14px;
        padding: 6px 10px;
        cursor: pointer;
        border-radius: 3px 3px 3px 3px;

        &.active,&:hover {
            color: #0052D9;
            background: #F2F3FF;
        }
    }
}

.imgprev {
    width: 100vw;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
        max-width: 100%;
        max-height: 100%;
        display: block;
    }
}

.footerForm {
    margin-left: 200px;
}

.formBox {
    width: 600px;
    margin-top: 40px;
}

.btnText {
    color: #0052d9 !important;
}

.dialogForm {
    ::v-deep .el-form-item {
        margin-bottom: 10px;
    }

    ::v-deep.el-form--label-top .el-form-item__label {
        padding: 0;
    }
}

.add {
    background: #0052d9;
    color: #fff;
    border: none;
}

.delBtn {
    background: #e7e7e7;
    color: #000;
    border: none;
}

.open {
    width: 52px;
    height: 32px;
    background: #e3f9e9;
    border-radius: 3px 3px 3px 3px;
    border: 1px solid #2ba471;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 400;
    font-size: 14px;
    color: #2ba471;
}

.close {
    width: 52px;
    height: 32px;
    background: #d8d8d8;
    border-radius: 3px 3px 3px 3px;
    border: 1px solid #767676;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 400;
    font-size: 14px;
    color: #767676;
}

.statusBox {
    width: 100%;
    display: flex;
    justify-content: center;
}

.status_div {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 66px;
    height: 32px;
    background: #ffffff;
    border-radius: 3px;
    border: 1px solid #e7e7e7;
    font-size: 14px;
    background: #f3f3f3;
    color: rgba(0, 0, 0, 0.9);
    line-height: 1;

    &.jxz {
        background: #f2f3ff;
        border: 1px solid #0052d9;
        color: #0052d9;
    }

    &.ywc {
        background: #e3f9e9;
        border: 1px solid #2ba471;
        color: #2ba471;
    }
}

.img {
    width: 38px;
    height: 38px;
}

.img_box {
    display: flex;
    justify-content: center;
    gap: 10px;
}

.el-select {
    width: 100%;
}
</style>